import React, { useState, useEffect } from "react";
import { LeftPage, LeftTopBox, LeftBottomBox } from "./style";
import { ModuleTitle } from "../../style/globalStyledSet";
import { BorderBox12, BorderBox13 } from "@jiaminghi/data-view-react";
import TrafficSituation from "./charts/TrafficSituation";
import UserSituation from "./charts/UserSituation";
import { getLeftPageData } from "../../services/index";

const Index = () => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        getLeftPageData()
            .then((response) => {
                console.log("数据请求成功", response);
                setData(response);
                setLoading(false);
            })
            .catch((err) => {
                console.error("数据请求失败", err);
                setError(err.message);
                setLoading(false);
            });
    }, []); // 空数组作为第二个参数，意味着这个 effect 只在组件挂载时运行一次

    if (loading) {
        return <div>Loading...</div>; // 在数据加载时显示加载指示器
    }

    if (error) {
        return <div>Error: {error}</div>; // 在发生错误时显示错误消息
    }

    const { userSitua, trafficSitua, accessFrequency, peakFlow } = data || {};
    return (
        <LeftPage>
            {/* 顶部图表 */}
            <LeftTopBox>
                <BorderBox12 className="left-top-borderBox12">
                    <div className="left-top">
                        <ModuleTitle>
                            <i className="iconfont">&#xe78f;</i>
                            <span>今日流量态势</span>
                        </ModuleTitle>
                        <div className="title-dis">
                            <span>
                                平均接纳次数(小时):
                                <span className="title-dis-keyword">{accessFrequency}次</span>
                            </span>
                            <span>
                                流量峰值:
                                <span className="title-dis-keyword">{peakFlow}M</span>
                            </span>
                        </div>
                        {/* 图表 */}
                        <TrafficSituation trafficSitua={trafficSitua}></TrafficSituation>
                    </div>
                </BorderBox12>
            </LeftTopBox>

            {/* 底部图表 */}
            <LeftBottomBox>
                <BorderBox13 className="left-bottom-borderBox13">
                    <div className="left-bottom">
                        <ModuleTitle>
                            <i className="iconfont">&#xe88e;</i>
                            <span>用户数据状态</span>
                        </ModuleTitle>
                        {/* 图表 */}
                        <UserSituation userSitua={userSitua}></UserSituation>
                    </div>
                </BorderBox13>
            </LeftBottomBox>
        </LeftPage>
    );
};

export default Index;
